/*
 * @Description: 
 * @Author: HuRrongChao
 * @Date: 2025-01-14 16:59:10
 * @LastEditors: HuRrongChao
 * @LastEditTime: 2025-01-15 16:59:40
 */
import { Barrage } from './barrage'

export class Barrages {
  constructor(options) {
    if (!options.canvas || !options.video) return

    Object.assign(this, options)

    // 初始化 canvas
    this.canvas.width = this.video.clientWidth
    this.canvas.height = this.video.clientHeight
    this.context = this.canvas.getContext('2d')

    // 保存弹幕数据
    this.barrages = this.data.map(item => new Barrage(item, this))

    // 是否播放弹幕
    this.isPlay = false
  }

  setBarrage(data) {
    this.data.push(data)
    this.barrages.push(new Barrage(data, this))
  }

  clear() {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
  }

  render() {
    // 清空画布
    this.clear()
    // 绘制新的画布
    this.renderBarrages()

    if (this.isPlay) {
      requestAnimationFrame(this.render.bind(this))
    }
  }

  // 绘制弹幕
  renderBarrages() {
    // 获取当前视频的时间
    const time = this.video.currentTime
    this.barrages.forEach(item => {
      if (item.flag && item.time <= time) {
        if (!item.isInit) {
          item.init()
          item.isInit = true
        }
        item.x = item.x - item.speed

        if (this.x < -this.width) {
          this.flag = false
        }
        item.render()
      }
    })
  }

  pause() {
    this.isPlay = false
    console.log('pause')
  }
}
